﻿using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;


namespace UnitEditorExpand.EditScene
{
    public class EditorSceneUtil
    {
        /// <summary>
        /// 获取|场景路径信息
        /// </summary>
        public static void GetPaths(string[] searchInFolders, out List<string> output)
        {
            output = new();

            var guids = AssetDatabase.FindAssets("t:Scene", searchInFolders);
            foreach (var guid in guids)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);

                if (File.Exists(path))
                    output.Add(path);
            }

            output.Sort((a, b) => Path.GetFileName(a).CompareTo(Path.GetFileName(b)));
        }

        /// <summary>
        /// 激活|选项菜单
        /// </summary>
        public static void DOMenuActive(Rect rect)
        {
            EditorSceneUtil.GetPaths(new string[] { "Assets" }, out var paths);

            var menu = new GenericMenu();
            var currentPath = SceneManager.GetActiveScene().path;

            foreach (var path in paths)
            {
                var sceneName = Path.GetFileNameWithoutExtension(path);
                var folderName = Path.GetFileName(Path.GetDirectoryName(path));
                var isActive = path == currentPath;

                // 添加场景菜单项
                menu.AddItem(
                    new GUIContent($"{folderName}/{sceneName}"),
                    isActive,
                    () => EditorSceneUtil.DOSceneChange(path)
                );
            }

            menu.DropDown(rect);
        }

        /// <summary>
        /// 切换|场景
        /// </summary>
        public static void DOSceneChange(string scenePath)
        {
            if (EditorApplication.isPlaying)
            {
                EditorUtility.DisplayDialog("警告","运行模式下禁止切换场景", "OK");
                return;
            }


            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                EditorSceneManager.OpenScene(scenePath);
            }
        }

        /// <summary>
        /// 查询|场景
        /// </summary>
        public static void DOSceneLocate(string scenePath)
        {
            EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<SceneAsset>(scenePath));
        }
    }
}
